﻿// For an introduction to the Blank template, see the following documentation:
// http://go.microsoft.com/fwlink/?LinkId=232509

/// <reference path="/js/memento.js" />

(function () {
    "use strict";
    
    WinJS.Binding.optimizeBindingReferences = true;

    var app = WinJS.Application;
    var activation = Windows.ApplicationModel.Activation;

    var canvas, ctx;
    var originator, caretaker;
    var doDraw=false, pointerDeviceType;

    app.onactivated = function (args) {
        if (args.detail.kind === activation.ActivationKind.launch) {
            if (args.detail.previousExecutionState !== activation.ApplicationExecutionState.terminated) {
                // TODO: This application has been newly launched. Initialize
                // your application here.
            } else {
                // TODO: This application has been reactivated from suspension.
                // Restore application state here.
            }
            args.setPromise(WinJS.UI.processAll());

            canvas = document.querySelector("#demoCanvas");
            var appBar = document.querySelector("#appBar").winControl;
            appBar.show();

            ////ponemos el canvas a fullscreen
            canvas.width = document.body.clientWidth;
            canvas.height = document.body.clientHeight;

            //obtenemos el context para pintar
            ctx = canvas.getContext("2d");

            //usamos los tres eventos para activar el pincel y pintar
            canvas.addEventListener("MSPointerDown", startDrawing);
            canvas.addEventListener("MSPointerUp", stopDrawing);
            canvas.addEventListener("MSPointerMove", draw);

            // creamos el originator sobre nuestro canvas
            // y un caretaker de 20 niveles
            originator = new CanvasState.originator(canvas);
            caretaker = new CanvasState.caretaker(20);

            //lo primero que haremos será añadir el canvas vacío como memento.
            caretaker.addMemento(originator.saveToMemento());

            document.getElementById('cmdUndo').winControl.addEventListener("click", function () {
                if (caretaker.canUndo)
                    originator.restoreFromMemento(caretaker.getUndoMemento());
            });

            document.getElementById('cmdRedo').winControl.addEventListener("click", function () {
                if (caretaker.canRedo)
                    originator.restoreFromMemento(caretaker.getRedoMemento());
            });

           
            cmdClear.winControl.addEventListener("click",
                function (e) {
                    //todo ask for confirmation
                    var ask = Windows.UI.Popups.MessageDialog("Are you sure to delete?");
                    ask.commands.append(new Windows.UI.Popups.UICommand("Yes"));
                    ask.commands.append(new Windows.UI.Popups.UICommand("No"));

                    ask.showAsync().done(function (command) {
                        if (command.label == "Yes") {
                            ctx.clearRect(0, 0, canvas.width, canvas.height);
                            caretaker.addMemento(originator.saveToMemento());
                        }
                    });
                });
        }
    };

    function startDrawing(e) {
        doDraw = true;
        var pointer = Windows.UI.Input.PointerPoint.getCurrentPoint(e.pointerId)
        pointerDeviceType = pointer.pointerDevice.pointerDeviceType;
        draw(e);
    }

    function stopDrawing(e) {
        doDraw = false;
        caretaker.addMemento(originator.saveToMemento(0, 0, canvas.width, canvas.height));
    }

    function draw(e) {
        if (doDraw) {
            //cambiamos entre tres colores según el id del puntero
            var id = e.pointerId % 3;
            var rgb = [0, 0, 0];
            rgb[id] = 255;

            //cambiamos el grosor según el puntero (ratón=fino, lápiz=mediano, táctil=grueso)
            var width = 10;
            switch (pointerDeviceType) {
                case Windows.Devices.Input.PointerDeviceType.mouse:
                    width = 10;
                case Windows.Devices.Input.PointerDeviceType.pen:
                    width = 20;
                    break;
                case Windows.Devices.Input.PointerDeviceType.touch:
                    width = 40;
            }

            //pintamos un círculo en el contexto 2d en la posición del movimiento
            ctx.beginPath();
            ctx.arc(e.clientX, e.clientY, width, 0, 2 * Math.PI, false);
            ctx.fillStyle = "rgb(" + rgb.join(",") + ")";
            ctx.fill();
        }
    }


    app.oncheckpoint = function (eventObject) {
        // TODO: This application is about to be suspended. Save any state
        // that needs to persist across suspensions here. You might use the
        // WinJS.Application.sessionState object, which is automatically
        // saved and restored across suspension. If you need to complete an
        // asynchronous operation before your application is suspended, call
        // eventObject.setPromise().
    };

    app.start();
})();
